/*================================================================
*   Copyright (C) 2020 Sangfor Ltd. All rights reserved.
*   
*   文件名称：tcp_process.cpp
*   创 建 者：Ann
*   创建日期：2020年06月21日
*   描    述：
*
================================================================*/

#include "tcp_svr.hpp"
#include <pthread.h>

#define CHECK_RET(p) if(p == false) {return -1;}

void* thread_start(void* arg)
{
    pthread_detach(pthread_self());
    TcpSvr* newts = (TcpSvr*)arg;
    //处理客户端的请求，并且回复
    while(1)
    {
        std::string buf;
        newts->Recv(&buf);
        printf("Client tell me [%s]\n", buf.c_str());

        printf("send client data: ");
        fflush(stdout);
        buf.clear();
        std::cin >> buf;

        newts->Send(buf);
    }
    newts->Close();
    delete newts;
    return NULL;
}

int main()
{
    TcpSvr listen_ts;
    CHECK_RET(listen_ts.CreateSocket());
    CHECK_RET(listen_ts.Bind("172.16.99.129", 19999));
    CHECK_RET(listen_ts.Listen());

    while(1)
    {
        TcpSvr* newts = new TcpSvr();
        struct sockaddr_in cli_addr;
        CHECK_RET(listen_ts.Accept(newts, &cli_addr));

        printf("Hava a new connect [%s][%d]\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));

        pthread_t tid;
        int ret = pthread_create(&tid, NULL, thread_start, (void*)newts);
        if(ret < 0)
        {
            perror("pthread_create");
            return 0;
        }
    }
    listen_ts.Close();
    return 0;
}
